/* OpenSSL headers */
#include <stdio.h>
#include "openssl/bio.h"
#include "openssl/ssl.h"
#include "openssl/err.h"

// 一个使用BIO的客户端的例子
// 流程:
// <1> BIO_new_connect("localhost:5678") 建立一个connect bio
// <2> BIO_do_connect(bio)    调用该函数连接到服务器端
// <3> 使用BIO_write和BIO_read来发送和接收数据.
int main(int argc, char **argv) {
  BIO *bio;
  char *wbuf = "this is a c -> s msg";
  char rbuf[128];
  memset(rbuf, 0, 128);

  /* Initializing OpenSSL */
  SSL_load_error_strings();
  ERR_load_BIO_strings();
  OpenSSL_add_all_algorithms();
  

  bio = BIO_new_connect("localhost:5678");
  if(bio == NULL)
  {
    printf("BIO_new_connect error\n");
    return -1;
  }
  if(BIO_do_connect(bio) <= 0)
  {
    printf("BIO_do_connect error\n");
    BIO_free_all(bio);
    return -1;
  }
  printf("client connected to the server\n");

  if(BIO_write(bio, wbuf, strlen(wbuf)) <= 0)
  {
    printf("BIO_write error\n");
    BIO_free_all(bio);
    return -1;
  }

  if(BIO_read(bio, rbuf, 128) <= 0) {
    printf("BIO_read error\n");
    BIO_free_all(bio);
    return -1;
  }
  printf("client# %s\n", rbuf);

  BIO_free_all(bio);
  return 0;


}
